<?php
	function extendedEncoding($data) {
		$max = max($data);
		$map = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-.';
		$len = strlen($map);
		
		$chd = '';
		for ($i = 0; $i < count($data); $i++) {
			$scaled = floor($len * $len * $data[$i] / $max);
			if ($scaled > ($len * $len) - 1) {
				$chd .= '..';
			} elseif($scaled < 0) {
				$chd .= '__';
			} else {
				$quotient = floor($scaled / $len);
				$remainder = $scaled - $len * $quotient;
				$chd .= $map[$quotient] . $map[$remainder];
			}
		}
		
		return $chd;
	}

	class Point {
		public $x, $y;
		function __construct($x, $y) {
			$this -> x = $x;
			$this -> y = $y;
		}
	}

	require_once '../classes/Config.class.php';
	require_once '../classes/Database.class.php';
	
	$Config = new Config();
	$DB = new Database();
	
	$Max = new Point(1920, 1080);
	$Symbols = array();
	$Time = 1299565255;
	
	$sql = $DB -> select('DISTINCT `Symbol`', 'Processed_Ftse', false, true);
	while ($row = $DB -> row($sql)) {
		$symbol = $row['Symbol'];
		if (!in_array($symbol, $Symbols)) $Symbols[] = $symbol;
	}
	
	foreach ($Symbols as $symbol) {
		$sql = $DB -> select('*', 'Storage_Ftse', "`Symbol` = '$symbol' AND Timestamp > $Time", false, 'Timestamp', 'ASC');
		$Data = array();
	
		while ($row = $DB -> row($sql)) {
			$Data['bid'][] = (double) $row['Bid'];
			$Data['ask'][] = (double) $row['Ask'];
			$Data['vol'][] = (double) $row['Volume'];
		}
		
		foreach (array('bid', 'ask', 'vol') as $type) {
			if (!isset($Data[$type])) {
				continue;
			}
			$max = max($Data[$type]);
			$min = min($Data[$type]);
			$url = 'https://chart.googleapis.com/chart?chid=' . md5(uniqid(rand(), true));
			$chd = 'e:' . extendedEncoding($Data[$type]);
			$chart = array(
				'cht' => 'lc',
				'chxt' => 'y',
				'chxr' => '0,' . $min . ',' . $max,
				'chs' => '750x400',
				'chds' => $min . ',' . $max,
				'chd' => $chd
			);
			
			$c = stream_context_create(
				array(
					'http' => array(
						'method' => 'POST',
						'content' => http_build_query($chart),
						'header' => 'Content-type: application/x-www-form-urlencoded'
					)
				)
			);
			
			$ih = fopen($url, 'rb', false, $c);
			if (!$ih) exit;
			$img = '';
			while (!feof($ih)) {
				$img .= fread($ih, 4092);
			}
			fclose($ih);
			
			$path = realpath('../../../graphs/');
			$h = fopen($path . '\\' . $symbol . '-' . $type . '.png', 'wb');
			fwrite($h, $img);
			fclose($h);
		}
	}
?>